<template>
      <div class="goods-body-box">
            <el-col :span="24" class="goods-header">
                  <el-page-header @back="goBack" content="详情页面"></el-page-header>
            </el-col>
            <el-col :span="5" class="min-height"></el-col>
            <el-col :span="14" class="goods-body">
                  <el-col :span="12" class="goods-img-box">
                        <img v-if="goods.img.length==0" :src="$url+'/upload/none.png'" alt=""/>
                        <el-carousel v-else trigger="click" height="500px" :autoplay="false">
                              <el-carousel-item v-for="(imgItem,index) in goods.img" :key="index">
                                    <el-image style="height: 500px" :src="$url+(imgItem.path)" fit="contain"></el-image>
                              </el-carousel-item>
                        </el-carousel>
                  </el-col>
                  <el-col :span="12">
                        <el-col :span="24" class="goods-name">{{goods.goodsName}}</el-col>
                        <el-col :span="24" class="goods-price">价格 : <span>￥{{goods.goodsPrice}}</span></el-col>
                        <el-col :span="24" class="goods-status">余量 : <span>{{goods.stock==0?'缺货':goods.stock}}</span></el-col>
                        <el-col :span="24" class="goods-status">上架时间 : <span>{{formatDate(goods)}}</span></el-col>
                        <el-col :span="24" class="buy-box">
                              购买数量: <el-input-number v-model="buy.num" controls-position="right" :min="1" :max="goods.stock"></el-input-number>
                        </el-col>
                        <el-col :span="24" class="buy-button-box">
                              <el-button type="primary" @click="addCart">加入购物车</el-button>
                              <el-button type="warning" @click="buyGoods">立即购买</el-button>
                        </el-col>
                  </el-col>
                  <el-col :span="24" class="goods-description" v-html="goods.description"></el-col>
            </el-col>
            <el-col :span="5" class="min-height"></el-col>


            <el-dialog title="创建订单" :visible.sync="formVisible" width="40%" @close='cancel'>
                  <el-form>
                        <el-form-item label='商品编号：' :label-width='formLabelWidth'>
                              {{goods.id}}
                        </el-form-item>
                        <el-form-item label='商品名称：' :label-width='formLabelWidth'>
                              {{goods.goodsName}}
                        </el-form-item>
                        <el-form-item label='商品单价：' :label-width='formLabelWidth'>
                              ￥{{goods.goodsPrice}}
                        </el-form-item>
                        <el-form-item label='购买数量：' :label-width='formLabelWidth'>
                              {{buy.num}}
                        </el-form-item>
                        <el-form-item label='总价：' :label-width='formLabelWidth'>
                              ￥{{buy.num*goods.goodsPrice}}
                        </el-form-item>
                       <el-form-item label='收货地址：' :label-width='formLabelWidth'>
                              <el-button type="primary" disabled size="mini" v-if="addr.length==0">请添加收货地址</el-button>
                              <el-select v-else v-model="buy.addr" placeholder="请选择" size="mini">
                                    <el-option v-for="item in addr" :key="item.id" :label="item.addr+','+item.phone" :value="item"></el-option>
                              </el-select>
                        </el-form-item>
                  </el-form>
                  <div slot="footer" class="dialog-footer">
                        <el-button @click="cancel">取 消</el-button>
                        <el-button type="primary" @click="pay">确认订单</el-button>
                  </div>
            </el-dialog>
            <!--接口返回的html代码渲染在页面上-->
            <div id="payDiv" v-html="payCont"></div>
      </div>
</template>

<script>
export default {
      props: [],
      data() {
            return {
                  formLabelWidth: "100px",
                  formVisible:false,
                  goods:{
                        id:'',
                        goodsName:'',
                        goodsPrice:'',
                        description:'',
                        stock:0,
                        createTime:'',
                        img:[]
                  },
                  buy:{
                        num:1,
                        addr:'',
                        remittance:''
                  },
                  addr:[],//我的收货地址
                  remittance:[],// 付款方式
                  
                  //需要传到接口的必要参数
                  payForm: {
                        body: "",
                        outTradeNo: "",
                        subject: "",
                        totalAmount: "",
                  },
                  payCont: "",
            }
      },
      methods:{
            pay() {
                  if(this.buy.addr==''){
                        this.$message({
                              type:'error',
                              message:'必填项不能空'
                        })
                        return;
                  }

                  this.getWidoutTradeNo();//订单号
                  this.payForm.subject=this.goods.goodsName;
                  this.payForm.totalAmount=this.buy.num*this.goods.goodsPrice;
                  this.payForm.body=this.goods.goodsName;
                  this.payForm.returnUrl=window.location.href
                  this.payForm.notifyUrl=window.location.href

                  window.sessionStorage.setItem("payForm",JSON.stringify(this.buy));
                  let format = new FormData();
                  Object.keys(this.payForm).map((key) => {
                        format.append(key, this.payForm[key]);
                  });
                  this.$axios({
                        method: "post",
                        url: this.$url + "/pay/aliPay",
                        data: format,
                  }).then((res) => {
                        this.payCont=res.data.data.content;
                        /**
                         * this.$nextTick稍微解释一下：this.payCont 进行赋值的时候是异步的
                         * (1)如果不加this.$nextTick：有可能出现this.payCont还没有渲染完毕，我这边就submit了，这个时候控制台就会报找不到这个submit
                         * （2）加this.$nextTick：就是确保我已经渲染完成了，你去获取这个class完成提交。
                         *
                         */
                        this.$nextTick(() => {
                              //使用原生js去获取到渲染在页面上的from表单，我们手动的提交请求，转到支付页面
                              let payId =
                                    document.getElementsByName(
                                          "punchout_form"
                                    )[0];
                              //提交
                              payId.submit();
                        });
                  });
            },
            //生成订单编号---根据日期生成
            getWidoutTradeNo() {
                  let vNow = new Date();
                  let sNow = "";
                  sNow += String(vNow.getFullYear());
                  sNow += String(vNow.getMonth() + 1);
                  sNow += String(vNow.getDate());
                  sNow += String(vNow.getHours());
                  sNow += String(vNow.getMinutes());
                  sNow += String(vNow.getSeconds());
                  sNow += String(vNow.getMilliseconds());
                  this.payForm.outTradeNo = sNow;
            },
            addCart(){
                  this.$root.loading=true;
                  let formData=new FormData();
                  formData.append('goodsId',this.goods.id);
                  formData.append('goodsNum',this.buy.num);
                  this.$axios({
                        method: "POST",
                        url: this.$url + "/client/shoppingCart/add",
                        data: formData,
                  });
            },
            submit(){
                  let buyOrder=JSON.parse(window.sessionStorage.getItem('payForm'));
                  let formData=new FormData();
                  formData.append("id",this.$route.query.out_trade_no);
                  formData.append("state",1);

            
                  let orderList=[{
                        orderId:this.$route.query.out_trade_no,
                        goodsId:this.$route.params.id,
                        goodsNum:buyOrder.num
                  }];
                  formData.append("orderLists",JSON.stringify(orderList));
                  formData.append("addr",buyOrder.addr.addr);
                  formData.append("mode","支付宝");
                  formData.append("phone",buyOrder.addr.phone);
                  formData.append("name",buyOrder.addr.name);
                  this.$axios({
                        url:this.$url+'/client/shoppingOrder/add',
                        method:'POST',
                        data:formData
                  }).then(()=>{
                        this.$message({
                              type:'success',
                              message:'购买成功'
                        })
                        this.$router.push('/admin/home');
                  })
            },
            goAddr(){
                  this.$router.push('/my/myAddr');
            },
            buyGoods(){
                  // 判断库存余量 是否为零
                  if(this.goods.stock < this.buy.num){
                        this.$message({
                              type:'error',
                              message:'库存不足'
                        })
                        return;
                  }else if(JSON.parse(window.sessionStorage.getItem('admin'))==null){
                        this.$message({
                              type:'error',
                              message:'需要登录'
                        })
                        return;
                  }
                  this.initAddr();
                  // this.initRemittance();
                  // 判断是否登录
                  this.$axios.get(this.$url+'admin/index/').then(
                        ()=>{
                              this.formVisible=true;
                        }
                  )
            },
            cancel() {
                  this.formVisible = false;
            },
            goBack(){
                  this.$router.go(-1);
            },
            /**格式化日期 */ 
            formatDate(row) {
                  let date = new Date(row.createTime);
                  let month =
                        date.getMonth() + 1 < 10
                              ? "0" + (date.getMonth() + 1)
                              : date.getMonth() + 1;
                  let day =
                        date.getDate() < 10
                              ? "0" + date.getDate()
                              : date.getDate();
                  return (
                        date.getFullYear() +
                        "-" +
                        month +
                        "-" +
                        day
                  );
            },
            initAddr(){
                  this.$axios
                        .get(
                              this.$url +
                                    "/client/addr/list?page=0&pageSize=20"
                        )
                        .then((response) => {
                              this.addr = response.data.data.list;
                        });
            },
            initGoods(){
                  this.$axios.get(this.$url+"/client/goods/info?id="+this.$route.params.id).then(res=>{
                        this.goods=res.data.data.info;
                  })
            }
      },
      mounted() {
            this.$root.loading=true;
            if(this.$route.query.out_trade_no){
                  this.submit();
            }else{
                  this.initGoods();
            }
            
      },
};
</script>

<style lang="less" scoped>
.goods-body-box{
      background-color: #AFD2FC;
}
.goods-header{
      padding: 20px 0 50px 20px;
}
.goods-img-box{
      padding: 10px 30px;

      img{
            height: 500px;
            width: 100%;
            border-radius: 10px;
      }
}
.goods-name{
      line-height: 80px;
      font-size: 20px;
      font-weight: 700;
}
.goods-status{
      height: 50px;
      line-height: 50px;
      background-color: #F0EFEF;
      padding: 0 10px;
      font-size: 14px;
      font-weight: 700;
      color: gray;
      span{
            color: #FF4400;
      }
}
.goods-price{
      height: 50px;
      line-height: 50px;
      background-color: #F0EFEF;
      padding: 0 10px;
      font-size: 14px;
      font-weight: 700;
      color: gray;
      span{
            color: #FF4400;
      }
}
.buy-box{
      height: 150px;
      line-height: 150px;
      font-weight: 700;
}

.goods-description{
      font-size: 14px;
      line-height: 40px;
      // font-weight: 700;
      font-size: 14px;
}
.buy-button-box{
      display: flex;
      justify-content: right;
      
      .buy-button{
            width: 140px;
            height: 40px;
            background-color: #FFEDED;
            line-height: 38px;
            border: 1px solid red;
            color: red;
            text-align: center;
            cursor: pointer;
            margin-left: 30px;
      }
}
</style>